package cn.xiaowenjie.common.aop;

import cn.xiaowenjie.common.beans.ResultBean;
import cn.xiaowenjie.common.exceptions.CheckException;
import cn.xiaowenjie.common.exceptions.UnloginException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 处理和包装异常
 * 主要就是打印日志和捕获异常，异常要区分已知异常和未知异常，其中未知的异常是我们重点关注的，可以做一些邮件通知啥的，已知异常可以再细分一下，可以不同的异常返回不同的返回码：
 * Reference: https://xwjie.github.io/rule/aop.html#aop%E5%AE%9E%E7%8E%B0-2
 * @author 肖文杰
 */
@Slf4j
@Aspect
@Component
@Order(-99)
public class ControllerAOP {
    /**
     * 返回ResultBean的所有方法都是切点
     */
    @Pointcut("execution(public cn.xiaowenjie.common.beans.ResultBean *(..))")
    public void controllerMethod() {
    }

    @Around("controllerMethod()")
    public Object handlerControllerMethod(ProceedingJoinPoint pjp) {
        long startTime = System.currentTimeMillis();

        ResultBean<?> result;

        try {
            //方法的返回结果,统计controller中方法耗时
            result = (ResultBean<?>) pjp.proceed();
            log.info(pjp.getSignature() + " use time: " + (System.currentTimeMillis() - startTime));
        } catch (Throwable e) {
            result = handlerException(pjp, e);
        }

        return result;
    }

    /**
     * 封装异常信息，注意区分已知异常（自己抛出的）和未知异常
     */
    private ResultBean<?> handlerException(ProceedingJoinPoint pjp, Throwable e) {
        ResultBean<?> result = new ResultBean();

        // 已知异常
        if (e instanceof CheckException) {
            result.setMsg(e.getLocalizedMessage());
            result.setCode(ResultBean.FAIL);
        }
        // 自己抛出的
        else if (e instanceof UnloginException ) {
            result.setMsg("Unlogin");
            result.setCode(ResultBean.NO_LOGIN);
        }
        //shiro异常： 登陆失败，如密码错误
        else if (e instanceof IncorrectCredentialsException) {
            result.setMsg("Login failed. Try xwjie/123456");
            result.setCode(ResultBean.FAIL);
        }
        // shiro异常：没有权限
        else if (e instanceof UnauthorizedException) {
            result.setMsg("NO PERMISSION: " + e.getMessage());
            result.setCode(ResultBean.NO_PERMISSION);
        }
        //  shiro抛出
        else if (e instanceof AuthorizationException) {
            result.setMsg("Unlogin");
            result.setCode(ResultBean.NO_LOGIN);
        } else {
            log.error(pjp.getSignature() + " error ", e);

            //TODO 未知的异常，应该格外注意，可以发送邮件通知等
            result.setMsg(e.toString());
            result.setCode(ResultBean.FAIL);
        }

        return result;
    }
}
